<?php

/**
 * wk  80342014
 * ============================================================================
 * *   wk  
 * *
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: lib_yang.php 17217 2011-01-19 06:29:08Z liubo $
*/





/**
 * openid  需要发送的 用户 openid 。
 * type    需要发送的信息类型 
 1 下綫注冊        2 新羊通知        3 新订单提醒   
 4 分红发放通知    5  推广购买通知   6 下线首次购买 
 7  分红通知       8  本金返还       9  一元活动中奖
 10 我想要活动通知 11  提现申请      12 耳号更新
 * @access  public
 * @return  void
 */
function wx_msg($openid = '',$type='30',$arr = array())
{
	$sql = "SELECT * FROM ".  $GLOBALS['ecs']->table('weixin_config') ." WHERE `id` = 1";
	$wei = $GLOBALS['db'] -> getRow($sql);
	if($openid){
		$openid = $GLOBALS['db'] -> getOne("select wxid from ".  $GLOBALS['ecs']->table('users')  ." where wxid = '$openid' or user_id = '$openid'");
	}
	 
	if(empty($openid)){
		return true;
	}
	/* 下线注册  */
	
	if($type == 1){
		$title = "邀请好友注册成功通知";
		$url = "http://".$_SERVER['HTTP_HOST']."/user.php?act=whole_money&change_type=50";
		$contentStr=" 好友名称：{$arr['mobile_phone_mi']} \r\n 注册时间：{$arr['reg_time']} \r\n 主人,您的好友 {$arr['mobile_phone_mi']} 已经接受邀请,{$arr['mobile_phone_mi']} TA 完成注册 ,奖励主人您{$arr['ycommission']}元" ;
	}elseif ($type == 2){
		$title = "新羊上线通知";
		$arr['start_date'] = local_date($GLOBALS['_CFG']['time_format'], $arr['start_date']);
		$arr['end_date'] = local_date($GLOBALS['_CFG']['time_format'], $arr['end_date']);
		
		$url = "http://".$_SERVER['HTTP_HOST']."/sheep.php?act=details&id=".$arr['sheep_id'];
		$contentStr=" 新羊名称：{$arr['sheep_name']} \r\n 开始购买时间：{$arr['start_date']} \r\n 购买截止时间 ：{$arr['end_date']} \r\n 请及时关注," ;
	}
	elseif ($type == 3){
		$title = "新订单提醒";
		$arr['add_time'] = local_date($GLOBALS['_CFG']['time_format'], gmtime());
		$arr['sheep_name'] = $GLOBALS['db']->getOne("SELECT sheep_name FROM " . $GLOBALS['ecs']->table('sheep') . " WHERE  sheep_id = '". $arr['sheep_id'] ."' "); 
		$url = "http://".$_SERVER['HTTP_HOST']."/user.php?act=buy_recordinfo&id=".$arr['order_id'];
		$contentStr=" 羊只名称：{$arr['sheep_name']} \r\n 购买时间：{$arr['add_time']} \r\n 数量 ：{$arr['sheep_number']}只 \r\n 金额：{$arr['sheep_price']}\r\n" ;
	}
	elseif ($type == 4){
		$title = "分红发放通知";
		$arr['add_time'] = local_date($GLOBALS['_CFG']['time_format'], $arr['add_time']);
		$arr['times'] = local_date($GLOBALS['_CFG']['time_format'], gmtime());
		$arr['sheep_name'] = $GLOBALS['db']->getOne("SELECT sheep_name FROM " . $GLOBALS['ecs']->table('sheep') . " WHERE  sheep_id = '". $arr['sheep_id'] ."' "); 
		$url = "http://".$_SERVER['HTTP_HOST']."/user.php?act=buy_recordinfo&id=".$arr['order_id'];
		$contentStr=" 您购买的：{$arr['sheep_name']} 已经发放分红了 \r\n 购买时间：{$arr['add_time']} \r\n 数量 ：{$arr['sheep_number']}只 \r\n 金额：{$arr['sheep_price']}\r\n 开始分红时间:{$arr['times']}" ;
	}
	elseif ($type == 5){
		$title = "推广购买通知";
		$arr['add_time'] = local_date($GLOBALS['_CFG']['time_format'], $arr['add_time']);
		$arr['times'] = local_date($GLOBALS['_CFG']['time_format'], gmtime());
	
		$user = get_user_s($arr['user_id']);
		$url = "http://".$_SERVER['HTTP_HOST']."/user.php?act=shepherd";
		$contentStr=" 您推荐的用户：{$user['mobile_phone_mi']} 下单了 \r\n 下单时间：{$arr['add_time']} \r\n 数量 ：{$arr['sheep_number']}只 \r\n 金额：{$arr['sheep_price']}\r\n " ;
	}
	elseif ($type == 6){
		$title = "推荐用户首次购买通知";
		$arr['add_time'] = local_date($GLOBALS['_CFG']['time_format'], $arr['add_time']);
		$arr['times'] = local_date($GLOBALS['_CFG']['time_format'], gmtime());
		$user = get_user_s($arr['user_id']);
		$url = "http://".$_SERVER['HTTP_HOST']."/user.php?act=shepherd";
		$contentStr=" 您推荐的用户：{$user['mobile_phone_mi']} 首次下单了 \r\n 下单时间：{$arr['add_time']} \r\n 数量 ：{$arr['sheep_number']}只 \r\n 金额：{$arr['sheep_price']}\r\n奖励金额：{$arr['ycommission']}，继续推荐朋友来吧...... " ;
	}
	elseif ($type == 7){
		$title = "分红发放通知";
		$arr['add_time'] = local_date($GLOBALS['_CFG']['time_format'], $arr['add_times']);
		$arr['times'] = local_date($GLOBALS['_CFG']['time_format'], gmtime());
		$url = "http://".$_SERVER['HTTP_HOST']."/user.php?act=whole_money&change_type=52";
		$contentStr=" 您购买的：{$arr['sheep_name']} 分红啦 \r\n 下单时间：{$arr['add_time']} \r\n 分红时间 ：{$arr['times']} \r\n 分红金额：{$arr['fenhong']}\r\n " ;

	}
	elseif ($type == 8){
		$title = "本金返还通知";
		$arr['add_time'] = local_date($GLOBALS['_CFG']['time_format'], $arr['add_time']);
		$arr['times'] = local_date($GLOBALS['_CFG']['time_format'], gmtime());
		$url = "http://".$_SERVER['HTTP_HOST']."/user.php?act=whole_money&change_type=53";
		$contentStr=" 您购买的：{$arr['sheep_name']} 本金返还啦 \r\n 下单时间：{$arr['add_time']} \r\n 返还时间 ：{$arr['times']}只 \r\n 返还金额：{$arr['quankuan']}\r\n " ;
	}
 	elseif ($type == 9){
		$title = "一元抢购中奖通知";
		$arr['add_time'] = local_date($GLOBALS['_CFG']['time_format'], $arr['add_time']);
		$arr['times'] = local_date($GLOBALS['_CFG']['time_format'], gmtime());
		$url = "http://".$_SERVER['HTTP_HOST']."/user.php?act=huodong";
		$contentStr=" 您参加的的：一元活动中奖啦！！！ \r\n 中奖码：{$arr['zjm']} \r\n 赶快去看看吧 . . . . . . " ;
	} 
	elseif ($type == 10){
		$title = "我想要活动通知";
		$arr['add_time'] = local_date($GLOBALS['_CFG']['time_format'], $arr['add_time']);
		$arr['times'] = local_date($GLOBALS['_CFG']['time_format'], gmtime());
		$url = "http://".$_SERVER['HTTP_HOST']."/user.php?act=huodong";
		$contentStr=" 您参加的的：我想要活动完成啦！！！ \r\n 赶快去看看吧 . . . . . . " ;
	}	
	elseif ($type == 11){
		$title = "提现提交通知";
		$arr['add_time'] = local_date($GLOBALS['_CFG']['time_format'], gmtime());
		$arr['times'] = local_date($GLOBALS['_CFG']['time_format'], gmtime());
		$url = "http://".$_SERVER['HTTP_HOST']."/user.php?act=whole_money&change_type=1";
		// $contentStr="您的提现申请已成功提交！！！\r\n <font color='#000'><b>提现金额：<b></font><font color='#ffad41'> {$arr['amount']}</font> \r\n <font color='#000'><b>提现时间：<b></font><font color='#ffad41'> {$arr['add_time']} </font> \r\n 工作日8:30-17:30的提现，到账时间预计在24小时之内 " ;
		$contentStr="您的提现申请已成功提交！！！\r\n 提现金额： {$arr['amount']} \r\n 提现时间： {$arr['add_time']} \r\n 工作日8:30-17:30的提现，到账时间预计在24小时之内 " ;
	}
	elseif ($type == 12){
		$title = "订单状态更新";
		$arr['add_time'] = local_date($GLOBALS['_CFG']['time_format'], gmtime());
		$arr['times'] = local_date($GLOBALS['_CFG']['time_format'], gmtime());
		$url = "http://".$_SERVER['HTTP_HOST']."/user.php?act=sheep_order_list";

		$contentStr="您的订单状态已经更新\r\n 订单编号： {$arr['order_id']} \r\n 订单状态： 羊只入圏   " ;
	}
 
	
	
	elseif ($type == 30){
		$title = "您好";
		$url = "http://".$_SERVER['HTTP_HOST']."/index.php";
		$contentStr=" 平台正在升级...... " ;
	}
    
	if(!empty($openid)){
		$wxinfo=curlgetcontents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$wei['appid']}&secret={$wei['appsecret']}");
		$wxinfo=  json_decode($wxinfo);
		$data='{
				"touser":"'.$openid.'",
				"msgtype":"news",
				"news":{
					"articles": [
					 {
						 "title":"'. $title .'",
						 "description":"'.$contentStr.'",
						 "url":"'.$url.'"
					 }
					 ]
				}
		}';

	 $code = curlgetcontents('https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$wxinfo->access_token,$data);
	 $res = json_decode($code);
 
	 return true;
	}
}
function curlgetcontents($url,$data=''){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    if(!empty($data)){
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }else{
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;  
      curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; 
    }
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	 // curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
 
    $res = curl_exec($ch);	
    curl_close($ch); 
    return $res;
}
	
/**
 *  根据卡 返回卡类型
 *  card   6228481552887309119
 *  bankList   卡类型
 */
function bankInfo($card,$bankList) 
{ 
  $card_8 = substr($card, 0, 8); 
  if (isset($bankList[$card_8])) { 
	return $bankList[$card_8]; 
	// return; 
  } 
  $card_6 = substr($card, 0, 6); 
  if (isset($bankList[$card_6])) { 
	return $bankList[$card_6]; 
	// return; 
  } 
  $card_5 = substr($card, 0, 5); 
  if (isset($bankList[$card_5])) { 
	return $bankList[$card_5]; 
	// return; 
  } 
  $card_4 = substr($card, 0, 4); 
  if (isset($bankList[$card_4])) { 
	return $bankList[$card_4]; 
	// return; 
  } 
  return '该卡号信息暂未录入'; 
} 
/**
 * 获取用户中心默认页面所需的数据
 *
 * @access  public
 * @param   int         $user_id            用户ID
 *
 * @return  array       $info               默认页面所需资料数组
 */
function get_user_s($user_id)
{
    $user_bonus = get_user_bonus();

    $sql = "SELECT pay_points, user_money, smsfz, reg_time, province,pay_password,  city, touxiang, smname, credit_line, last_login,  mobile_phone, is_validated FROM " .$GLOBALS['ecs']->table('users'). " WHERE user_id = '$user_id'";
    $row = $GLOBALS['db']->getRow($sql);
	 $info = array();
	if(empty($row['mobile_phone'])){
		$info['mobile_phone_mi'] = '';
		$info['mobile_phone_type'] = '0';
	}else{
		$pattern1 = "/(1\d{1,2})\d\d(\d{0,3})/"; 
		$info['mobile_phone_mi'] = preg_replace($pattern1, "\$1*****\$3", $row['mobile_phone']);
		$info['mobile_phone_type'] = '1';
	}
 
   
    $info['username']  = stripslashes($_SESSION['user_name']);
    $info['shop_name'] = $GLOBALS['_CFG']['shop_name'];
    $info['integral']  = $row['pay_points'] . $GLOBALS['_CFG']['integral_name'];
    /* 增加是否开启会员邮件验证开关 */
    $info['is_validate'] = ($GLOBALS['_CFG']['member_email_validate'] && !$row['is_validated'])?0:1;
    $info['credit_line'] = $row['credit_line'];
    $info['smname'] = $row['smname'];
    $info['mobile_phone'] = $row['mobile_phone'];
    $info['user_money'] = $row['user_money'];
    $info['touxiang'] = $row['touxiang'];
    $info['reg_time'] = local_date($GLOBALS['_CFG']['date_format'], $rows['reg_time']);
	
	if($row['smsfz']){
		$pattern2 = "/(1\d{1,2})\d\d(\d{4,8})/"; 
		$info['smsfz'] =preg_replace($pattern2, "\$1****\$3", $row['smsfz']);
	}else{
		$info['smsfz'] = $row['smsfz'];
		
	}
	$info['province_name'] = '';
	$info['city_name'] = '';
	if($row['province'] > 0){
		$info['province_name'] = $GLOBALS['db']->getOne("select region_name from ".$GLOBALS['ecs']->table('region'). " where region_id = '". $row['province'] ."'");
	} 
	if($row['city'] > 0){
		$info['city_name'] = $GLOBALS['db']->getOne("select region_name from ".$GLOBALS['ecs']->table('region'). " where region_id = '".  $row['city'] ."'");
	}
	
	
	
	$info['pay_password'] = $row['pay_password'];
    $info['formated_credit_line'] = price_format($info['credit_line'], false);

    //如果$_SESSION中时间无效说明用户是第一次登录。取当前登录时间。
    $last_time = !isset($_SESSION['last_time']) ? $row['last_login'] : $_SESSION['last_time'];

    if ($last_time == 0)
    {
        $_SESSION['last_time'] = $last_time = gmtime();
    }

    $info['last_time'] = local_date($GLOBALS['_CFG']['time_format'], $last_time);
    $info['surplus']   = price_format($row['user_money'], false);
    $info['bonus']     = sprintf($GLOBALS['_LANG']['user_bonus_info'], $user_bonus['bonus_count'], price_format($user_bonus['bonus_value'], false));

    $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('order_info').
            " WHERE user_id = '" .$user_id. "' AND add_time > '" .local_strtotime('-1 months'). "'";
    $info['order_count'] = $GLOBALS['db']->getOne($sql);

    include_once(ROOT_PATH . 'includes/lib_order.php');
    $sql = "SELECT order_id, order_sn ".
            " FROM " .$GLOBALS['ecs']->table('order_info').
            " WHERE user_id = '" .$user_id. "' AND shipping_time > '" .$last_time. "'". order_query_sql('shipped');
    $info['shipped_order'] = $GLOBALS['db']->getAll($sql);

    return $info;
}

/**
 * openid  需要发送的 用户 openid 。
 * type    需要发送的信息类型 1 下綫注冊  2 新羊通知
 * @access  public
 * @return  void
 */
function get_user_set($user_id)
{
	$arr = $GLOBALS['db']->getRow("SELECT * FROM " . $GLOBALS['ecs']->table('users') . " WHERE  user_id = '". $user_id ."'"); 
	
	if($arr['wxid']){
		$arr['wx'] = $GLOBALS['db']->getRow("SELECT * FROM " . $GLOBALS['ecs']->table('weixin_user') . " WHERE  wxid = '". $arr['wxid'] ."'");
	}
	if($arr){
		if(empty($arr['mobile_phone']) ){
			$arr['mobile_phone_mi'] = '';
		}else{
			$pattern1 = "/(1\d{1,2})\d\d(\d{0,3})/"; 
			$arr['mobile_phone_mi'] = preg_replace($pattern1, "\$1*****\$3", $arr['mobile_phone']);
			$arr['mobile_phone_type'] = '1';
		}
	}
	
	
	
    return $arr;
}



/**
 * 获得 当前用户购买的 羊的耳号
 * @return  integer
 */
function get_this_sheep_erhao($user_id )
{
	$count = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('sheep_erhao') . " WHERE  user_id = '". $user_id ."' and erhao != ''"); 
    return $count;
}
/**
 * 获得当前用户购买的 羊列表
 *
 * @access  public
 * @param   integer     $cat_id
 * @param   integer     $page
 * @param   integer     $size
 *
 * @return  array
 */
function get_this_sheep_erhaolist($page = 1, $size = 20 ,$user_id ='')
{
    $sql = "SELECT *  FROM " .$GLOBALS['ecs']->table('sheep_erhao') .  " WHERE 1  and user_id = '". $user_id ."'  and erhao != ''  ORDER BY id DESC";

    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page-1) * $size);

    $arr = array();
    if ($res)
    {
        while ($row = $GLOBALS['db']->fetchRow($res))
        {
			$row['qishu'] =  $GLOBALS['db']->getOne("select s.qishu from " .$GLOBALS['ecs']->table('sheep') ." as s LEFT JOIN  ".$GLOBALS['ecs']->table('sheep_order') ." as o ON o.sheep_id = s.sheep_id where o.order_id = '$row[order_id]'");
			
			
			
            $arr[]  = $row;
        }
    }

    return $arr;
}


/**
 * 获得 当前用户购买的 羊的总订单
 * @return  integer
 */
function get_this_sheep_count($user_id )
{
	$count = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('sheep_order') . " WHERE  user_id = '". $user_id ."' and pay_time > 0 "); 
    return $count;
}

/**
 * 获得当前用户购买的 羊列表
 *
 * @access  public
 * @param   integer     $cat_id
 * @param   integer     $page
 * @param   integer     $size
 *
 * @return  array
 */
function get_this_sheep_list($page = 1, $size = 20 ,$user_id ='')
{
    $sql = "SELECT *  FROM " .$GLOBALS['ecs']->table('sheep_order') .  " WHERE 1  and user_id = '". $user_id ."' and pay_time > 0  ORDER BY add_time DESC";

    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page-1) * $size);

    $arr = array();
    if ($res)
    {
        while ($row = $GLOBALS['db']->fetchRow($res))
        {
			$bonus_queue =  $GLOBALS['db']->getRow("select * from ".$GLOBALS['ecs']->table('sheep_bonus_queue') ." where order_id = '".  $row['order_id'] ."'  order by bonus_times desc ");
			if($bonus_queue['bonus_times'] > gmtime()){
				$row['money'] = '---';
				$row['bonus_time'] = "已分完";
			}else{
				$row['money'] = $bonus_queue['money'];
				$row['bonus_time'] = $bonus_queue['bonus_time'];
			}
			  
			
			$row['count'] =  $GLOBALS['db']->getOne("select count(*) from ".$GLOBALS['ecs']->table('sheep_bonus_queue') ." where bonus_times > '". gmtime() ."' and order_id = '". $row['order_id'] ."'" );
			
			$sheep=  $GLOBALS['db']->getRow("select sheep_name ,qishu ,sheep_pinzhong ,bonus,cycle ,price from ".$GLOBALS['ecs']->table('sheep') ." where sheep_id = '". $row['sheep_id'] ."'" );

			$row['sheep_name'] =   $sheep['sheep_name'];
			$row['cycle'] =   $sheep['cycle'];
			$row['price'] =   $sheep['price'];
			$row['qishu'] =   $sheep['qishu'];
			$row['bonus'] =   $sheep['bonus'];
			$row['sheep_pinzhong'] =   isset($sheep['sheep_pinzhong']) ? $sheep['sheep_pinzhong'] : '青山羊';
			$row['add_times'] = $row['add_time'];
			$row['add_time']         =  local_date('Y-m-d H:i', $row['add_time']);
			
			/* 取最后一次返的时间  计算 */
			$start =  gmtime();
			$endtime =  $bonus_queue['bonus_times']; /* 最后一次分红时间  */
			$shengyu = $endtime - $start  > 0 ? $endtime - $start  : 0;
			$shengyuday = Sec2Time($shengyu); /* 还剩多少分红时间 */
			 
			if($shengyuday['days'] > 0){
				$row['day'] = '剩余<br>'. $shengyuday['days'] .'天';
			}else{
				$row['day'] = '已分完';
			}
			$kaishitime = $endtime - $row['add_times'];
			$kaishiday = Sec2Time($kaishitime);
			$bili = round(360 - ($shengyuday['days'] / $kaishiday['days'] * 360));
			if($bili > 10){
				$str = substr($bili, -1); //mn
				if($str >= 5){
					$bili = $bili + 10 - $str;
				}else{
					$bili = $bili - $str;
				}
			}
			$row['bili'] =   $bili;
	
			
            $arr[]  = $row;
        }
    }

    return $arr;
}


function Sec2Time($time){
    if(is_numeric($time)){
    $value = array(
      "years" => 0, "days" => 0, "hours" => 0,
      "minutes" => 0, "seconds" => 0,
    );
    if($time >= 31556926){
      $value["years"] = floor($time/31556926);
      $time = ($time%31556926);
    }
    if($time >= 86400){
      $value["days"] = floor($time/86400);
      $time = ($time%86400);
    }
    if($time >= 3600){
      $value["hours"] = floor($time/3600);
      $time = ($time%3600);
    }
    if($time >= 60){
      $value["minutes"] = floor($time/60);
      $time = ($time%60);
    }
    $value["seconds"] = floor($time);
    //return (array) $value;
    // $t=$value["years"] ."年". $value["days"] ."天"." ". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
    return $value;
    
     }else{
    return (bool) FALSE;
    }
 }
 
/**
 * 获得 当前用户的 本月应该得到的分红金额
 *
 * @param   integer     $user_id
 *
 * @return  integer
 */
function get_this_money($user_id )
{	
	//  获取当前月的开始时间、结束时间
	$time = local_date('Y-m-d', gmtime());
	$stare_time = local_date('Y-m-01 00:00:00', strtotime($time));
	$end_time = local_date('Y-m-d 23:59:59', strtotime("$stare_time +1 month -1 day"));
	// $end_time = local_date('Y-m-d ', strtotime("$stare_time +1 month -1 day"));
	$stime = strtotime($stare_time);
	$etime = strtotime($end_time);
	$sql = "select SUM(money) from ".$GLOBALS['ecs']->table('sheep_bonus_queue') ." where user_id = '$user_id' and bonus_times < $etime and bonus_times > $stime";
	return $GLOBALS['db']->getOne($sql);
}
/**
 * 获得 当前用户的 还没有返的样款
 *
 * @param   integer     $user_id
 *
 * @return  integer
 */
function get_wei_this_money_fh($user_id )
{	
	$sql = "select order_id from ".$GLOBALS['ecs']->table('sheep_bonus_queue') ." where user_id = '$user_id' and bonus_fanquankuan = 1 and bonus_times > '". gmtime() ."' ";
	$order =  $GLOBALS['db']->getAll($sql);
	if($order){
		$id  = array();
		foreach($order as $k => $v){
			$id[] = $v['order_id'];
		}
		$money = $GLOBALS['db']->getOne("select sum(sheep_price) from ".$GLOBALS['ecs']->table('sheep_order') ." where order_id in (". implode(',',$id) .")");
		return $money;
		
	}else{
		return 0;
	}
}

/**
 * 获得 当前用户的 还没有返的羊款
 *
 * @param   integer     $user_id
 *
 * @return  integer
 */
function get_wei_this_money($user_id )
{	
	$sql = "select SUM(money) from ".$GLOBALS['ecs']->table('sheep_bonus_queue') ." where user_id = '$user_id' and bonus_times > '". gmtime() ."' ";
	$money = $GLOBALS['db']->getOne($sql);
	// return $GLOBALS['db']->getOne($sql);
	// return  sprintf('%.1f', (float)$money); 
	return sprintf("%.1f",substr(sprintf("%.2f", $money), 0, -1)); 
}
/**
 * 获得 当前用户的  已经返
 *
 * @param   integer     $user_id
 *
 * @return  integer
 */
function get_leiji_money($user_id )
{	
	$sql = "select SUM(money) from ".$GLOBALS['ecs']->table('sheep_bonus_queue') ." where user_id = '$user_id' and bonus_times < '". gmtime() ."' ";
	return $GLOBALS['db']->getOne($sql);
}

/**
 * 获得 青山羊币的的 记录 总数量 
 *
 * @param   integer     $cat_id
 *
 * @return  integer
 */
function get_user_money_count($user_id ,$account_type='user_money',$change_type = 0)
{
	$where = '';
	if($change_type > 1 ){
		$where = " and change_type = '$change_type'";
	}else {
		$where = " and change_type in (0,1)";
	}
    /* 获取记录条数 */
    $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('account_log').
           " WHERE user_id = '$user_id'" .
           " AND $account_type <> 0  $where ";
    $record_count = $GLOBALS['db']->getOne($sql);
 
    return $record_count;
}
/**
 * 获得当前用户购买的 羊列表
 *
 * @access  public
 * @param   integer     $cat_id
 * @param   integer     $page
 * @param   integer     $size
 *
 * @return  array
 */
function get_user_money_list($page = 1, $size = 20 ,$user_id ='',$account_type = 'user_money',$change_type = 0)
{
	//获取余额记录
	$where = '';
	if($change_type > 1){
		$where  = " and change_type = '$change_type'";
	}else if($change_type == 1) {
		$where = " and change_type in (0,1)";
	}
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('account_log') .
           " WHERE user_id = '$user_id'" .
           " AND $account_type <> 0  $where" .
           " ORDER BY log_id DESC";;

    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page-1) * $size);

    $account_log = array();
	while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $row['change_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['change_time']);
        $row['type'] = $row[$account_type] > 0 ? '增加' : '减少';
        $row['user_moneys'] = $row['user_money'];
        $row['user_money'] = price_format(abs($row['user_money']), false);
        $row['frozen_money'] = price_format(abs($row['frozen_money']), false);
        $row['rank_points'] = abs($row['rank_points']);
        $row['pay_points'] = abs($row['pay_points']);
        $row['short_change_desc'] = sub_str($row['change_desc'], 60);
        $row['amount'] = $row[$account_type];
        $account_log[] = $row;
    }

    return $account_log;
}




/**
 * 获得羊的总数量  
 *
 * @param   integer     $cat_id
 *
 * @return  integer
 */
function get_sheep_count($types = '1' )
{
    global $db, $ecs;
  
	$count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('sheep') . " WHERE  1 and types = '". $types ."'"); 
    return $count;
}

/**
 * 获得羊列表
 *
 * @access  public
 * @param   integer     $cat_id
 * @param   integer     $page
 * @param   integer     $size
 *
 * @return  array
 */
function get_sheep_list($page = 1, $size = 20 ,$types='1')
{
      $sql = "SELECT *  FROM " .$GLOBALS['ecs']->table('sheep') .
               " WHERE 1 and types = '". $types ."' ORDER BY sheep_id DESC, add_time DESC";

    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page-1) * $size);

    $arr = array();
    if ($res)
    {
        while ($row = $GLOBALS['db']->fetchRow($res))
        {
		 
			
			/* 清空已经到期的没有付款的羊 */
			delect_sheep_cart(array($row['sheep_id']));
 
			/* 默认是未开放 */
			$row['state'] = '1';
			$row['state_name'] = '未开放';
			/* 没有达到 开始时间售卖时间  */
			if($row['start_date'] > gmtime()){
				$row['state'] = '1';
				$row['state_name'] = '未开放';
				$row['solds'] = '';
				$row['data'] =  0;
				$row['textColor'] =  'rgb(0, 0, 0)';
			}else{
				
				/* 已经开始  库存大于 0 */
				if($row['start_date'] <= gmtime() && $row['ym_number'] < $row['number'] && $row['end_date'] >= gmtime()){
					$row['state'] = '2';
					$row['state_name'] = '抢购中';
					$row['solds'] = round($row['ym_number'] /$row['number']  * 100) . '%';
					$row['data'] =  $row['ym_number'] /$row['number'];
					$row['textColor'] =  'rgb(0, 0, 0)';
				}
				/* 已经开始  库存小于 等于  0 */
				elseif($row['start_date'] <= gmtime() || $row['ym_number'] >= $row['number'] || $row['end_date'] <= gmtime()){
					$row['state'] = '3';
					$row['state_name'] = '分红中';
					$row['solds'] = '分红中';
					$row['data'] =  1;
					$row['textColor'] =  'rgb(255, 255, 255)';
				}		
				/* 已经开始  库存小于 等于  0 */
				/*if($row['end_date'] <= gmtime()){
					$row['state'] = '3';
					$row['state_name'] = '分红中';
					$row['solds'] = '分红中';
					$row['data'] =  1;
					$row['textColor'] =  'rgb(255, 255, 255)';
				}	*/
				
			}
			
		 
			
			
			$row['state_yue'] = local_date("m-d", $row['start_date']);
			// $row['state_yue'] = date("m-d", $row['start_date']);
			$row['state_shi'] = local_date("H:i", $row['start_date']);
			// $row['state_shi'] = date("H:i", $row['start_date']);
			$row['ystart_date'] = local_date("Y-m-d", $row['start_date']);
			
			$row['sy_number'] = $row['number'] -  $row['ym_number'] ;
			$row['sold'] =  round($row['ym_number'] /$row['number']  * 100);
			// $row['solds'] =  $row['ym_number'] /$row['number'];
			$row['url']         =  build_uri('sheep', array('shid'=>$row['sheep_id']), $row['sheep_name']) ;
            $arr[]  = $row;
        }
    }

    return $arr;
}
/**
 * 获得羊详情
 *
 * @access  public
 * @param   integer     $id
 * @return  array
 */
function get_sheep_details($id){
	$sql = "select * from ".$GLOBALS['ecs']->table('sheep') ." where sheep_id = '".  intval($id) ."'";
	$res = $GLOBALS['db']->getRow($sql);
	if($res){
		$res['sy_number'] = $res['number'] - $res['ym_number'] ;
		$res['dq_time'] = gmtime() ;
		$res['kaishi_time'] =local_date('Y-m-d H:i', $res['start_date']);
		$res['cart_count'] = sheep_cart_count($id) ? sheep_cart_count($id)  : 0;
		
		/* 看訂單 有没有没有支付的 */
		$cart_count = $GLOBALS['db']->getOne("select sum(sheep_number) from ".$GLOBALS['ecs']->table('sheep_order') ." where sheep_id = '". $id ."' and (pay_time = '' or pay_time < 1)");
		$res['cart_count'] += $cart_count;
		$res['keyigomai'] = $res['sy_number'] - $res['cart_count'];
	}
 
	return $res;
}


/**
 * 获得 购买中的羊的总数量
 *
 * @access  public
 * @param   integer     $id
 * @return  array
 */
function sheep_cart_count($id){
	$sql = "select sum(sheep_number) from ".$GLOBALS['ecs']->table('sheep_cart') ." where sheep_id = '".  intval($id) ."'";
	$res = $GLOBALS['db']->getOne($sql);
	return $res;
}

/**
 * 获得 购买中的羊的总信息
 * 可以传用户的ID
 * @access  public
 * @param   integer     $user_id
 * @return  array
 */
function get_sheep_cart_list($user_id){
	/* 总数量  */
	$sheep_number = $GLOBALS['db']->getOne("select sum(sheep_number) from ".$GLOBALS['ecs']->table('sheep_cart') ." where user_id = '".  intval($user_id) ."'");
	/* 总价格  */
	$sheep_price = $GLOBALS['db']->getOne("select sum(sheep_price) from ".$GLOBALS['ecs']->table('sheep_cart') ." where user_id = '".  intval($user_id) ."'");
	/* 总价格  */
	$ids = $GLOBALS['db']->getAll("select cart_id from ".$GLOBALS['ecs']->table('sheep_cart') ." where user_id = '".  intval($user_id) ."'");
	$id = '';
	if($ids){
		foreach($ids as $k => $v){
			$id[$k] = $v['cart_id'];
		}
	}
	$id = implode(',',$id);

	$arr = array();
	$arr['sheep_number'] = $sheep_number;
	$arr['sheep_price'] = $sheep_price;
	$arr['id'] = $id;
	$arr['list'] = $GLOBALS['db']->getRow("select * from ".$GLOBALS['ecs']->table('sheep_cart') ." where user_id = '".  intval($user_id) ."'");
	return $arr;
}

/**
 *  清空 到期没有付款的羊
 *  羊的 ID
 * @access  public
 * @param   integer     
 * @return  array
 */
function delect_sheep_cart($arr = array()){
	if(empty($arr)){
		return true;
	}
	$time = gmtime();
	$GLOBALS['db']->query("DELETE FROM " .$GLOBALS['ecs']->table('sheep_cart'). " WHERE sheep_id in (". implode(',',$arr) .") and end_time <= $time ");	
	delect_sheep_cart_quanbu();	
	return true;
}
/**
 *  清空 所有 到期没有付款的羊
 *  羊的 ID
 * @access  public
 * @param   integer     
 * @return  array
 */
function delect_sheep_cart_quanbu(){

	$time = gmtime();
	$GLOBALS['db']->query("DELETE FROM " .$GLOBALS['ecs']->table('sheep_cart'). " WHERE  end_time <= $time ");		
	return true;
}
/**
 *  根据di清空 羊
 *  羊的 ID
 * @access  public
 * @param   integer     
 * @return  array
 */
function del_sheep_cart($id = 0){
	$GLOBALS['db']->query("DELETE FROM " .$GLOBALS['ecs']->table('sheep_cart'). " WHERE  cart_id = '". $id ."' ");		
	return true;
}

/**
 *  买羊成功之后 更新已卖
 *  羊的 sheep_id
 * @access  public
 * @param   integer     
 * @return  array
 */
function updata_sheep($sheep_id = 0,$num = 0){
	
	$sql="update ".$GLOBALS['ecs']->table('sheep')."set ym_number = ym_number + $num where sheep_id='$sheep_id'";
    $GLOBALS['db']->query($sql);	
	return true;
}
/**
 *   处理有的订单不付款 
 *  羊的 sheep_id
 * @access  public
 * @param   integer     
 * @return  array
 */
function weizhfu_order(){
	$time = gmtime() - 60 * $GLOBALS['_CFG']['locking_time'];
	$sql = "select sheep_id , sheep_number, order_id from " .$GLOBALS['ecs']->table('sheep_order')." where ( pay_time < 0 or pay_time = '' ) and  add_time <  $time ";
	$arr =  $GLOBALS['db']->getAll($sql);	
	/*  */
	if($arr){
		foreach($arr as $k => $v){
			$num = -$v['sheep_number'];
			updata_sheep($v['sheep_id'],$num);
			$GLOBALS['db']->query("DELETE FROM " .$GLOBALS['ecs']->table('sheep_order'). " WHERE  order_id = '". $v['order_id'] ."' and pay_time = '' ");		
		 
		}
	}
	return true;
}

/**
 *  获取没有支付的订单
 * @access  public
 * @param   integer     
 * @return  array
 */
function user_weizhfu_order($user_id){
	
	if($user_id <= 0){
		return false;
	}
	
	$time = gmtime() - 60 * $GLOBALS['_CFG']['locking_time'];
	$sql = "select * from " .$GLOBALS['ecs']->table('sheep_order')." where ( pay_time < 0 or pay_time = '' ) and  user_id = '". $user_id ."' order by add_time desc";
	$arr =  $GLOBALS['db']->getRow($sql);	
	/*  */
	if($arr){
		$arr['sytime'] = ($arr['add_time'] +  60 * $GLOBALS['_CFG']['locking_time']) - gmtime();
		// if($arr['sytime'] <= 0){
			// $GLOBALS['db']->query("DELETE FROM " .$GLOBALS['ecs']->table('sheep_order'). " WHERE  order_id = '". $arr['order_id'] ."' and pay_time = '' ");	
		// }
		
		
	}
	return $arr;
}



/**
 *  自己购买羊的详情
 * @access  public
 * @param   user_id   用户 ID     
 * @param   sheep_id  羊 ID     
 * @return  array
 */

function thissheep($user_id = 0,$sheep_id = 0){
	if($user_id <= 0 || $sheep_id <= 0){
		return true;
	}
	// $sql = "select * from " .$GLOBALS['ecs']->table('sheep_cart'). " where sheep_id = '". intval($sheep_id) ."' and user_id = '". intval($user_id) ."'";
	$sql = "select * from " .$GLOBALS['ecs']->table('sheep_cart'). " where  user_id = '". intval($user_id) ."'";
	$res = $GLOBALS['db']->getRow($sql);
	if($res){
		$res['sytime'] = $res['end_time'] - gmtime();
	}
	return $res;
}




/**
 *  获取用户的银行卡 指定卡
 *  sheep_id  羊的ID
 * @access  public
 * @param   array       $address
 * @return  bool
 */
function phb($sheep_id = 0,$type = 1)
{
	$list = array();
	if($type == 1){
		$sql = "select * from ".$GLOBALS['ecs']->table('sheep_order')." where sheep_id = '". $sheep_id ."' and state = 2 and pay_time > 0 order by pay_time desc ";
		$res = $GLOBALS['db']->getAll($sql);
 
	}elseif($type == 2){
		$sql = "select  user_id ,add_time , sum(sheep_number) as sheep_numbers  from ".$GLOBALS['ecs']->table('sheep_order')." where sheep_id = '". $sheep_id ."' and state = 2 GROUP BY user_id order by sheep_numbers desc  limit 10 ";
		$res = $GLOBALS['db']->getAll($sql);
	}
 
	if($res){
		foreach($res as$k => $v){
			$v['add_time'] = local_date($GLOBALS['_CFG']['time_format'], $v['add_time']);
			
			$user = $GLOBALS['db']->getRow("select user_name , mobile_phone ,nickname ,touxiang from  ".$GLOBALS['ecs']->table('users'). " where user_id = '". $v['user_id'] ."'");
			$pattern1 = "/(1\d{1,2})\d\d(\d{0,3})/"; 
			$mobile_phone = preg_replace($pattern1, "\$1*****\$3", $user['mobile_phone']);
			$v['mobile_phone'] = $mobile_phone;
			$v['nickname'] = $user['nickname'];
			$v['touxiang'] = $user['touxiang'];
			$list[] = $v;
		}
	}


	return $list;
}


/**
 *  获取购买羊的数量
 *
 * @access  public
 * @param   array       $address
 * @return  bool
**/
function get_sheep_info($orderid = 0){
	
    $order = $GLOBALS['db']->getRow("SELECT * FROM " .$GLOBALS['ecs']->table('sheep_order'). " WHERE order_id = '$orderid'");
	$order['add_times'] = $order['add_time'];
	$order['add_time'] = local_date($GLOBALS['_CFG']['time_format'], $order['add_time']);
	$order['times'] = local_date($GLOBALS['_CFG']['time_format'], gmtime());
	
	
	$user = $GLOBALS['db']->getRow("select * from ".$GLOBALS['ecs']->table('users')." where user_id = '$order[user_id]'");
	
	$order['smname'] = $user['smname'];
	$order['smsfz'] = $user['smsfz'];
	$order['mobile_phone'] = $user['mobile_phone'];
	$order['shouyi'] = $GLOBALS['db']->getOne("select sum(money) from ".$GLOBALS['ecs']->table('sheep_bonus_queue')." where order_id = '$orderid' and user_id = '$order[user_id]'");
	
	$order['yishouyi'] = $GLOBALS['db']->getOne("select sum(money) from ".$GLOBALS['ecs']->table('sheep_bonus_queue')." where order_id = '$orderid' and user_id = '$order[user_id]' and state = 1 ");
	
	$order['endtime'] = $GLOBALS['db']->getOne("select bonus_time from ".$GLOBALS['ecs']->table('sheep_bonus_queue')." where order_id = '$orderid' and user_id = '$order[user_id]' order by bonus_id desc");
	
	$goods = $GLOBALS['db']->getRow("select * from ".$GLOBALS['ecs']->table('sheep')." where sheep_id = '$order[sheep_id]'");
	$order['qishu'] = $goods['qishu'];
	$order['price'] = $goods['price'];
	$order['sheep_pinzhong'] = isset($goods['sheep_pinzhong']) ? $goods['sheep_pinzhong'] : '青山羊';
	$order['sheep_name'] =   $goods['sheep_name'];
	$order['cycle'] =   $goods['cycle'];
	$order['bonus'] =   $goods['bonus'];
	$order['sheep_pinzhong'] =   isset($goods['sheep_pinzhong']) ? $goods['sheep_pinzhong'] : '青山羊';

	$bonus_queue =  $GLOBALS['db']->getRow("select * from ".$GLOBALS['ecs']->table('sheep_bonus_queue') ." where order_id = '".  $order['order_id'] ."'  order by bonus_times desc ");
	
	/* 取最后一次返的时间  计算 */
	$start =  gmtime();
	$endtime =  $bonus_queue['bonus_times']; /* 最后一次分红时间  */
	$shengyu = $endtime - $start  > 0 ? $endtime - $start  : 0;
	$shengyuday = Sec2Time($shengyu); /* 还剩多少分红时间 */
	 
	if($shengyuday['days'] > 0){
		$order['day'] = '剩余<br>'. $shengyuday['days'] .'天';
	}else{
		$order['day'] = '已分完';
	}
	$kaishitime = $endtime - $order['add_times'];
	$kaishiday = Sec2Time($kaishitime);
	
	
	
	if($shengyuday['days'] > 0 && $kaishiday['days'] > 0){
		$bili = round(360 - ($shengyuday['days'] / $kaishiday['days'] * 360));
	}else{
		$bili = 360;
	}
	
	if($bili > 10){
		$str = substr($bili, -1); //mn
		if($str >= 5){
			$bili = $bili + 10 - $str;
		}else{
			$bili = $bili - $str;
		}
	}
	$order['bonus_times'] =  date("Y/m/d", $endtime) ;
	$order['shengdays'] =   $shengyuday['days'];
	$order['gongdays'] =   $kaishiday['days'];
	$order['yiday'] =   $kaishiday['days'] - $shengyuday['days'];
	$order['bili'] =   $bili;
	
 
	$order['yishouyilist'] = $GLOBALS['db']->getAll("select * from ".$GLOBALS['ecs']->table('sheep_bonus_queue')." where order_id = '$orderid' and user_id = '$order[user_id]' and state = 1 ");
	
	return $order;
}



/**
 *  获取购买羊的数量
 *
 * @access  public
 * @param   array       $address
 * @return  bool
**/
function get_this_count($user_id = 0){
    $count = $GLOBALS['db']->getOne("SELECT sum(sheep_number) FROM " .$GLOBALS['ecs']->table('sheep_order'). " WHERE user_id = '$user_id'");
	return $count;
}

/**
 *  获取最新的一只羊的信息
 *
 * @access  public
 * @param   array       $address
 * @return  bool
**/
function get_yang($type=1){
	
	$time = gmtime();
    $sql = 'SELECT * FROM ' .$GLOBALS['ecs']->table('sheep') . ' WHERE 1 and types = '. $type .'  ORDER BY  end_date DESC ,sheep_id desc';
    // $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('sheep') . " WHERE 1  and start_date < $time ORDER BY sheep_id DESC";
	$row = $GLOBALS['db']->getRow($sql);
	if($row){
		/* 清空已经到期的没有付款的羊 */
			delect_sheep_cart(array($row['sheep_id']));
	
			/* 默认是未开放 */
			$row['state'] = '1';
			$row['state_name'] = '未开放';
			/* 没有达到 开始时间售卖时间  */
			if($row['start_date'] > gmtime()){
				$row['state'] = '1';
				$row['state_name'] = '未开放';
				$row['solds'] = '';
				$row['data'] =  0;
				$row['textColor'] =  'rgb(0, 0, 0)';
			}
			/* 已经开始  库存大于 0 */
			elseif($row['start_date'] <= gmtime() && $row['ym_number'] < $row['number']){
				$row['state'] = '2';
				$row['state_name'] = '抢购中';
				$row['solds'] = round($row['ym_number'] /$row['number']  * 100) . '%';
				$row['data'] =  $row['ym_number'] /$row['number'];
				$row['textColor'] =  'rgb(0, 0, 0)';
			}
			/* 已经开始  库存小于 等于  0 */
			elseif($row['start_date'] <= gmtime() && $row['ym_number'] >= $row['number']){
				$row['state'] = '3';
				$row['state_name'] = '分红中';
				$row['solds'] = '分红中';
				$row['data'] =  1;
				$row['textColor'] =  'rgb(255, 255, 255)';
			}
			
			 
			$row['state_yue'] = local_date("m-d", $row['start_date']);
			// $row['state_yue'] = date("m-d", $row['start_date']);
			$row['state_shi'] = local_date("H:i", $row['start_date']);
			// $row['state_shi'] = date("H:i", $row['start_date']);
			
			$row['sy_number'] = $row['number'] -  $row['ym_number'] ;
			$row['sold'] =  round($row['ym_number'] /$row['number']  * 100);
			// $row['solds'] =  $row['ym_number'] /$row['number'];
			$row['url']         =  build_uri('sheep', array('shid'=>$row['sheep_id']), $row['sheep_name']) ;
	}
	return $row;
	
	
}




/**
 *  根据订单id 加入分成队列
 *
 * @access  public
 * @param   array    
 * @return  bool
 */
function bonus_queue($order_id){
	/* 验证 是否已经有了队列 没有 在进行队列 */
	$count = $GLOBALS['db']->getOne("select count(*) from ". $GLOBALS['ecs']->table('sheep_bonus_queue'). " where order_id = '$order_id'");
	if($count > 0){
		return false;
	}
	$order = $GLOBALS['db']->getRow("select * from ". $GLOBALS['ecs']->table('sheep_order'). " where order_id = '$order_id'");
	/* 如果分成时间大于 1个月 */
	if($order['cycle'] > 0){
		$data = array(
			'user_id' => $order['user_id'], /* 用户 id  */
			'money' => ($order['sheep_price'] * ( $order['bonus']/100)) * $order['sheep_number'],/* 本条订单返的金额 */
			'order_id' => $order['order_id']  /*  是哪条订单返的 */
		);
		/* 下订单的时间 */
		$bonus_times = $order['add_time'];
		$bonus_time = local_date($GLOBALS['_CFG']['time_format'], $bonus_times); 
		for($i = 0; $i < $order['cycle'] ; $i++){
			$bonus_time = date("Y-m-d H:i:s", strtotime("+1 months", strtotime($bonus_time)));
			$bonus_times = strtotime(date ($bonus_time));
			$data['bonus_time'] = $bonus_time;
			$data['bonus_times'] = $bonus_times;
			$num = $order['cycle'] - 1; 
			if($num == $i){
				$data['bonus_fanquankuan'] = 1; 
			}
			$GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('sheep_bonus_queue'), $data, 'INSERT');
		}	
	}
	/* 发货就是 认为是分红 */
	$userset = get_user_set($order['user_id']);
	if($userset['wxid'] && $userset['yz_fh_msg'] == 1){
		wx_msg($userset['wxid'],4,$order);
    }
	/* 验证是否是首次消费  并且超过 1000 */
	$count = $GLOBALS['db']->getOne("select count(*) from ". $GLOBALS['ecs']->table('sheep_order') ." where user_id = '". $order['user_id'] ."'");
 
	if($count == 1 && $order['sheep_price'] >= $GLOBALS['_CFG']['first_xiaofei'] && $GLOBALS['_CFG']['first_xiaofei_jiang'] > 0 && $userset['parent_id'] > 0){
		$parent_user = get_user_set($userset['parent_id']);
 
		if($parent_user['commission'] < $GLOBALS['_CFG']['commission']){
			/* 计算佣金 */
			$commission = $parent_user['commission'] + $GLOBALS['_CFG']['first_xiaofei_jiang'];/* 加上本次返的金額 不能大于上限 */
			$ycommission = $GLOBALS['_CFG']['first_xiaofei_jiang']; /* 应该返的佣金  */
			if($commission > $GLOBALS['_CFG']['commission']){
				$ycommission = $GLOBALS['_CFG']['commission'] - $parent_user['commission'];
			}
		 
			$order['ycommission'] = $ycommission;
			$txt = "推荐的用户首次下单,奖励金额".$ycommission;
			log_account_change($parent_user['user_id'], $ycommission, 0, 0, 0, $txt, ACT_SCXD); // 推荐的用户首次下单
			
			$sql = 'UPDATE ' . $GLOBALS['ecs']->table('users') . " SET `commission`= commission + $ycommission WHERE `user_id`='" . $parent_user['user_id'] . "'";
			$GLOBALS['db']->query($sql);
					
			if($parent_user['wxid']){
				wx_msg($parent_user['wxid'],6,$order);
			}
		}
		
		
		
		
	}
	
	
	
	return true;
}









/**
 *  添加或者修改 银行卡信息
 *
 * @access  public
 * @param   array       $address
 * @return  bool
 */
function update_bank($bank)
{
    $bank_id = intval($bank['bank_id']);
    unset($bank['bank_id']);

    if ($bank_id > 0)
    {
         /* 更新指定记录 */
        $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('user_bank'), $bank, 'UPDATE', 'bank_id = ' .$bank_id . ' AND user_id = ' . $bank['user_id']);
    }
    else
    {
        /* 插入一条新记录 */
        $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('user_bank'), $bank, 'INSERT');
        $bank_id = $GLOBALS['db']->insert_id();
    }
    return true;
}

/**
 *  获取用户的银行卡信息
 *
 * @access  public
 * @param   array       $address
 * @return  bool
 */
function get_banklist($user_id)
{
	
	$banklist = $GLOBALS['db']->getAll("SELECT * FROM ".$GLOBALS['ecs']->table('user_bank')." where user_id = '$user_id'");
	if($banklist){
		foreach($banklist as $k => $v){
			$banklist[$k]['weihao'] = substr($v['bank_num'],-4);
		}
	}
	
    return $banklist;
}

/**
 *  获取用户的银行卡 指定卡
 *
 * @access  public
 * @param   array       $address
 * @return  bool
 */
function get_bank($user_id,$bank_id)
{
	$banklist = $GLOBALS['db']->getRow("SELECT * FROM ".$GLOBALS['ecs']->table('user_bank')." where user_id = '$user_id' and bank_id = '$bank_id'");
	if($banklist){
		$banklist['weihao'] = substr($banklist['bank_num'],-4);
	}
	
    return $banklist;
}

/**
 * 删除一银行卡信息
 *
 * @access  public
 * @param   integer $id
 * @return  boolean
 */
function drop_bank($user_id,$bank_id)
{
    $sql = "SELECT bank_id FROM " .$GLOBALS['ecs']->table('user_bank') . " WHERE user_id = '$user_id' and bank_id = '$bank_id'";
    $uid = $GLOBALS['db']->getOne($sql);

    if ($uid > 0)
    {
        $sql = "DELETE FROM " .$GLOBALS['ecs']->table('user_bank') . " WHERE user_id = '$user_id' and bank_id = '$bank_id'";
        $res = $GLOBALS['db']->query($sql);
		 return true;
    }
    else
    {
      
        return false;
    }
}

 
 
/**
 * 处理分红记录  可以做成计划任务  然后每 5分钟执行一次
 * 每次只取 2000条  避免服务器卡死
 * @access  public
 * @param   integer $id
 * @return  boolean
 */
function handle_abonus(){
	$time = gmtime();
	$sql = "select * from ".$GLOBALS['ecs']->table('sheep_bonus_queue') ." where state = 0 and bonus_times < $time limit 2000";
	$res = $GLOBALS['db']->getAll($sql);
 
	if(empty($res)){
		return true;
	}else{
		foreach($res as $k => $v){
			/* 获取订单信息 */
			$sql =" select s.sheep_name , s.qishu from ". $GLOBALS['ecs']->table('sheep') ." as s RIGHT JOIN  ".  $GLOBALS['ecs']->table('sheep_order')  ." as o ON o.sheep_id = s.sheep_id  where o.order_id  = '$v[order_id]'";
			$row = $GLOBALS['db']->getRow($sql);
			 
			$text = $row['sheep_name']."第". $row['qishu'] ."期分红:".$v['money'];
			$userset = get_user_set($v['user_id']);
			$order = get_sheep_info($v['order_id']);
			$order['fenhong'] = $v['money'];
			
		
			if($v['money'] > 0){
				log_account_change($v['user_id'], $v['money'], 0, 0, 0, $text , ACT_FH); // 分红
				
				if($userset['wxid'] && $userset['yz_sy_msg'] == 1){
					wx_msg($userset['wxid'],7,$order);
				}
				
			}
			 
			
			/* 返全款 */
			if($v['bonus_fanquankuan'] == 1){
				$money = '';
				$money = $GLOBALS['db']->getOne("SELECT sheep_price from ". $GLOBALS['ecs']->table('sheep_order') ." where order_id = '$v[order_id]'");
				if($money > 0){
					$txt = $row['sheep_name']."第". $row['qishu'] ."期返全款:".$money;
					log_account_change($v['user_id'], $money, 0, 0, 0, $txt , ACT_FHYK); // 返全款
					
					$order['quankuan'] = $money;
					if($userset['wxid'] && $userset['yz_sy_msg'] == 1){
						wx_msg($userset['wxid'],8,$order);
					}
					
				}
			}	
			/* 更新订单为已返状态 */
			$sql="update ".$GLOBALS['ecs']->table('sheep_bonus_queue')."set state = 1 where bonus_id='$v[bonus_id]'";
			$GLOBALS['db']->query($sql);	

		}
		
		
	}

}


/**
 *  获取用户推广的下线
 *  
 * @access  public
 * @param   type  zc  gm
 * @return  boolean
 */
function get_xiaxian($type = 'zc',$user_id){
	if($user_id <= 0){
		return 0;
	}
	$count = 0;
	if($type == 'zc'){
		$count =  $GLOBALS['db']->getOne("SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('users')." where parent_id = '". $user_id ."'");	
	}elseif($type == 'gm'){
		$count =  $GLOBALS['db']->getOne("SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('sheep_order')." as s LEFT JOIN ".$GLOBALS['ecs']->table('users')." as u ON u.user_id = s.user_id where u.parent_id = '". $user_id ."'");	
	}
	return $count;
	
}


/**
 * 获得当前用户购买的 羊列表
 *
 * @access  public
 * @param   integer     $cat_id
 * @param   integer     $page
 * @param   integer     $size
 *
 * @return  array
 */
function get_xiaxian_list($page = 1, $size = 20 ,$user_id ='',$type = 'zc')
{
	
	if($type == 'zc'){
		$sql = "SELECT wxid,user_id,user_name FROM ".$GLOBALS['ecs']->table('users')." where parent_id = '". $user_id ."'";
	}
	elseif($type == 'gm'){
		$sql = "SELECT u.wxid,u.user_id,u.user_name FROM ".$GLOBALS['ecs']->table('sheep_order')." as s LEFT JOIN ".$GLOBALS['ecs']->table('users')." as u ON u.user_id = s.user_id where u.parent_id = '". $user_id ."' group by u.user_id ";
	}

    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page-1) * $size);

    $list = array();
	while ($row = $GLOBALS['db']->fetchRow($res))
    {
		if($row['wxid']){
			$arr = $GLOBALS['db']->getRow("SELECT * FROM ".$GLOBALS['ecs']->table('weixin_user')." WHERE wxid = '". $row['wxid'] ."'");
			$row['nickname'] = $arr['nickname'];
			$row['headimgurl'] = $arr['headimgurl'];
		}else{
			$row['nickname'] = $row['user_name'];
			$row['headimgurl'] = "themes/view/images/noimg.png";
		}
        $list[] = $row;
    }

    return $list;
}

/**
 * 获得当前活动是否存在 
 * @return  count
 */
function get_activitys_show($types = 2)
{
	$time = gmtime();
	return $GLOBALS['db']->getOne("SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('sheep')." where types = '". $types ."' and start_date < $time and end_date > $time ");
}



/**
 * 获得当前 可以参加的活动
 *
 * @access  public
 * @param   integer     $cat_id
 * @param   integer     $page
 * @param   integer     $size
 *
 * @return  array
 */
function get_activitys_show_list($page = 1, $size = 20 ,$user_id ='',$type = 'zc')
{
	
	if($type == 'zc'){
		$sql = "SELECT wxid,user_id,user_name FROM ".$GLOBALS['ecs']->table('users')." where parent_id = '". $user_id ."'";
	}
	elseif($type == 'gm'){
		$sql = "SELECT u.wxid,u.user_id,u.user_name FROM ".$GLOBALS['ecs']->table('sheep_order')." as s LEFT JOIN ".$GLOBALS['ecs']->table('users')." as u ON u.user_id = s.user_id where u.parent_id = '". $user_id ."' group by u.user_id ";
	}

    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page-1) * $size);

    $list = array();
	while ($row = $GLOBALS['db']->fetchRow($res))
    {
		if($row['wxid']){
			$arr = $GLOBALS['db']->getRow("SELECT * FROM ".$GLOBALS['ecs']->table('weixin_user')." WHERE wxid = '". $row['wxid'] ."'");
			$row['nickname'] = $arr['nickname'];
			$row['headimgurl'] = $arr['headimgurl'];
		}else{
			$row['nickname'] = $row['user_name'];
			$row['headimgurl'] = "themes/view/images/noimg.png";
		}
        $list[] = $row;
    }

    return $list;
}

/**
 * 获得当前活动 已购买人数
 * @return  count
 */
function get_activitys_gm_count($sheep_id)
{
	return $GLOBALS['db']->getOne("SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('sheep_yy')." where sheep_id = '". $sheep_id ."' ");
}

/**
 * 获得当前活动 当前用户是否购买
 * @return  count
 */
function this_yy($user_id = 0,$sheep_id = 0)
{	
	$arr = array();
	if($user_id <= 0 || $sheep_id <= 0){
		return $arr;
	} 
	$arr =  $GLOBALS['db']->getAll("SELECT number FROM ".$GLOBALS['ecs']->table('sheep_yy')." where sheep_id = '". $sheep_id ."' and user_id = '". $user_id ."'");
	return $arr;
}

/**
 * 获得当前活动  有多少人购买  
 * @return  count  group by  user_id
 */
function get_yy_count($sheep_id = 0)
{	
	$count =  $GLOBALS['db']->getOne("SELECT count(DISTINCT user_id) FROM ".$GLOBALS['ecs']->table('sheep_yy')." where sheep_id = '". $sheep_id ."'  ");
	return $count;
}
/**
 * 获得当前活动  有多少人购买  的记录
 *
 * @access  public
 * @param   integer     $cat_id
 * @param   integer     $page
 * @param   integer     $size
 *
 * @return  array
 */
function get_yy_count_list($page = 1, $size = 20 ,$sheep_id ='')
{

	$sql = "SELECT DISTINCT user_id FROM ".$GLOBALS['ecs']->table('sheep_yy')."  where sheep_id = '". $sheep_id ."' order by addtime desc ";
    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page-1) * $size);
    $list = array();
	while ($row = $GLOBALS['db']->fetchRow($res))
    {	
		$user = array();
		$user = get_user_set($row['user_id']);
		$row['user_name'] = isset($user['wx']['nickname']) ? trim($user['wx']['nickname']) : $user['mobile_phone_mi'] ;
		$row['goumaicishu'] = count(this_yy($row['user_id'],$sheep_id ));
		/* 取最后一次购买时间 */
		$endtime = $GLOBALS['db']->getOne("select addtime from " .$GLOBALS['ecs']->table('sheep_yy'). " where user_id = '". $row['user_id'] ."' and sheep_id = '". $sheep_id ."' order by addtime  desc");
		
		$row['endtime'] = local_date($GLOBALS['_CFG']['time_format'], $endtime); 
        $list[] = $row;
    }
    return $list;
}
/**
 * 获得当前活动   中奖记录
 * @return  array
 */
function get_zj($sheep_id){
	$arr =  $GLOBALS['db']->getRow("SELECT * FROM ".$GLOBALS['ecs']->table('sheep_yy')." where sheep_id = '". $sheep_id ."' and is_winning = 2  ");
	if($arr){
		$user = get_user_set($arr['user_id']);
		$arr['user'] = $user;
		$arr['name'] = isset($user['wx']['nickname']) ? trim($user['wx']['nickname']) : $user['mobile_phone_mi'] ;
		$arr['jilu'] = this_yy($arr['user_id'] ,$sheep_id) ;
		$arr['jilunum'] = count(this_yy($arr['user_id'] ,$sheep_id)) ;
	}
	return $arr;
}
/**
 * 获得当前活动   中奖
 * @return  array
 */

function winning($sheep_id){
	$sheep = get_sheep_details($sheep_id);
	$number = $sheep['number']; /*  目标次数 */
	$yishou =  get_activitys_gm_count($sheep_id);
	$zj = get_zj($sheep_id);
 
	/* 已卖的超过了 当前的  并且没有 中奖记录  验证  是否有中奖的  */
	if($yishou >= $number && empty($zj)){
		/* 随机取一个中奖的记录  */
		$sj =  $GLOBALS['db']->getRow("SELECT * FROM ".$GLOBALS['ecs']->table('sheep_yy')." where sheep_id = '". $sheep_id ."' and is_winning = 1  order by rand() LIMIT 1");
		if($sj){
			/* 购买羊支付  余额 */
			$time = gmtime();
			$dangqian = local_date($GLOBALS['_CFG']['time_format'], $time); 
			
			/* 默认时间 */
			$bonus_time_yue = $dangqian;
			$bonus_time = $time;
			$bonus_time_done = $time;
			if($sheep['cycle'] > 0){
				$bonus_time_yue = date("Y-m-d H:i:s", strtotime("+1 months", strtotime($dangqian)));
				$bonus_time = strtotime(date ($bonus_time_yue));
				$bonus_time_done_yue = date("Y-m-d H:i:s", strtotime("+".$sheep['cycle']." months", strtotime($dangqian)));
				$bonus_time_done = strtotime(date ($bonus_time_done_yue));
			}
			$userset = get_user_set($sj['user_id']);
			
			/* 价值  */
			$sheep_price = $sheep['jiazhi'] ;
	 
			$order = array(
				'sheep_id' => $sheep_id,/* 羊编号 */
				'user_id' => isset($sj['user_id']) ? $sj['user_id'] : $sj['user_id'],/* 用户编号 */
				'sheep_number' => 1,/* 数量  */
				'sheep_price' => $sheep_price,/* 价格  */
				'add_time' => $time,/* 时间  */
				'pay_type' => 'balance',/* 时间  */
				'pay_time' => gmtime(),/* 时间  */
				'state' => '2',/* 上级id  */
				'parent_id' => '',/* 上级id  */
				'hd_types' => '1',/* 活动类型  */
				'winning' => $sj['id'] ,/* 中奖 id  */
				'bonus' => $sheep['bonus'] / 12,/* 分红比例  */
				'cycle' => $sheep['cycle'],/* 分红月  */
				'bonus_time' => $bonus_time,/* 下一次分红时间  当前时间 加一个月  */
				'bonus_time_yue' => $bonus_time_yue,/* 下一次分红时间  当前时间 加一个月  */
				'bonus_time_done' => $bonus_time_done,/* 最终分红时间  */
				'bonus_time_done_yue' => $bonus_time_done_yue,/* 最终分红时间  */
			);		
			 
			$GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('sheep_order'), $order, 'INSERT');
			$sql = "UPDATE ". $GLOBALS['ecs']->table('sheep_yy') ." SET is_winning = '2'WHERE id= '". $sj['id'] ."'";
			$GLOBALS['db']->query($sql);
			$order_id = $GLOBALS['db']->insert_id();
		 
			/* 购买通知  */
			$order['order_id'] = $order_id;
			$order['zjm'] = $sj['number'];
			if($userset['wxid'] ){
				wx_msg($userset['wxid'],9,$order);
			}  
			
			// echo "<pre>"; print_r($order);die('----');
			/* 根据订单ID 生成排队分成队列 */
			bonus_queue($order_id);	
		}
		return true;
	}else{
		return true;
	}
}


/**
 * 获得当前用户 参加的过的活动
 * @return  count  group by  user_id
 */
function get_huodong_count($type = 1,$user_id)
{	
	/* 获取一元 记录 */
	if($type == 1){
		$count =  $GLOBALS['db']->getOne("SELECT count(DISTINCT sheep_id) FROM ".$GLOBALS['ecs']->table('sheep_yy')." where user_id = '". $user_id ."'  ");
	}elseif($type == 2){
		$count =  $GLOBALS['db']->getOne("SELECT count(*) FROM ".$GLOBALS['ecs']->table('sheep_me')." where user_id = '". $user_id ."'  ");
	}else{
		$count = 0;
	}
	return $count;
}
/**
 * 获得当前 用户参加的活动
 *
 * @access  public
 * @param   integer     $cat_id
 * @param   integer     $page
 * @param   integer     $size
 *
 * @return  array
 */
function get_huodong_list($page = 1, $size = 20 ,$type ='',$user_id ='')
{
	/* 获取一元 记录 */
	if($type == 1){
		$sql =  "SELECT DISTINCT sheep_id  FROM ".$GLOBALS['ecs']->table('sheep_yy')." where user_id = '". $user_id ."' order by addtime desc  ";
	}elseif($type == 2){
		$sql =  "SELECT  *  FROM ".$GLOBALS['ecs']->table('sheep_me')." where user_id = '". $user_id ."' order by addtime desc  ";
	}else{
		$sql = '';
	}
	// $sql = "SELECT DISTINCT user_id FROM ".$GLOBALS['ecs']->table('sheep_yy')."  where sheep_id = '". $sheep_id ."' order by addtime desc ";
    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page-1) * $size);
    $list = array();
	while ($row = $GLOBALS['db']->fetchRow($res))
    {	
		$sheep = array();
		if($type == 1){
			$sheep = get_sheep_details($row['sheep_id']);
			$zj = get_zj($row['sheep_id']);
			$sheep['is_kaijiang'] = 1;
			if($zj || $sheep['end_date'] <= gmtime()){
				$sheep['is_kaijiang'] = 2;
			}	
			$list[] = $sheep;
		}
		
		if($type == 2){
			$sheep = get_sheep_details($row['sheep_id']);
			$sheep['start'] = $row['start'];
			$sheep['id'] = $row['id'];
			$list[] = $sheep;
		}
		
        
    }
    return $list;
}








/**
 * 获得当前活动 我想要  有多少人购买  
 * @return  count  group by  user_id
 */
function get_me_count($sheep_id = 0,$user_id = 0)
{	
	$where = '';
	if($user_id > 0){
		$where = " and user_id = '". $user_id ."'";
	}
	$count =  $GLOBALS['db']->getOne("SELECT count(*) FROM ".$GLOBALS['ecs']->table('sheep_me')." where sheep_id = '". $sheep_id ."' $where  ");
	return $count;
}

/**
 * 获得当前活动 我想要  订单详情
 * @return  count  group by  user_id
 */
function get_wantshare_details($id = 0)
{	
	if($id <= 0){
		return array();
	}
	$wantshare =  $GLOBALS['db']->getRow("SELECT * FROM ".$GLOBALS['ecs']->table('sheep_me')." where id = '". $id ."'   ");
	
	/* 用户信息 */
	$wantshare['user'] = get_user_set($wantshare['user_id']);
	$yifu = get_wantshare_money($wantshare['id']); /* 已经减掉 */
	$sy_jine = $wantshare['money'] - $yifu ;
	$wantshare['sy_jine'] = $sy_jine > 0 ? $sy_jine : 0;

	$bili = round(360 - ($wantshare['sy_jine'] / $wantshare['money'] * 360));
	if($bili > 10){
		$str = substr($bili, -1); //mn
		if($str >= 5){
			$bili = $bili + 10 - $str;
		}else{
			$bili = $bili - $str;
		}
	}
	$wantshare['sheep'] =   get_sheep_details($wantshare['sheep_id']);;
	$wantshare['bili'] =   $bili;
	$wantshare['bfb'] =  round(( $yifu / $wantshare['money']) * 100 ,2);

	return $wantshare;
}

/**
 * 获得当前活动 已经有多少金额了
 * @return  count  group by  user_id
 */
function get_wantshare_money($id = 0)
{	
	$sql = "select sum(money) from ".$GLOBALS['ecs']->table('sheep_me_list')." where oid = '". $id .  "' and ( openid != '' or user_id != '' )";
	return $GLOBALS['db']->getOne($sql);
}

/**
 * 获得当前活动  砍价总人数
 * @return  count  group by  user_id
 */
function get_wantshare_count($id = 0)
{	
	$sql = "select count(*) from ".$GLOBALS['ecs']->table('sheep_me_list')." where oid = '". $id .  "' ";
	return $GLOBALS['db']->getOne($sql);
}

/**
 * 获得当前活动 砍价  列表
 * @return  count  group by  user_id
 */
function get_wantshare_list($page = 1, $size = 20 ,$id ='',$lxtype ='1')
{	

	/* 获取一元 记录 */
	$order = 'id desc';
	if($lxtype == 1){
		$order = ' addtime desc';
	}
	elseif($lxtype == 2){
		$order = ' money desc';
	}
	elseif($lxtype == 3){
		$order = ' addtime desc';
	}
	
	$sql = "select * from ".$GLOBALS['ecs']->table('sheep_me_list')." where oid = '". $id .  "' order by $order";

    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page-1) * $size);
    $list = array();
	while ($row = $GLOBALS['db']->fetchRow($res))
    {	
		$row['addtime'] = local_date($GLOBALS['_CFG']['time_format'], $row['addtime']); 
        $list[] = $row;
    }
    return $list;
	
}

/**
 * 获得 我想要活动结束
 * @return  count  group by  user_id
 */
function wantshare($id = 0)
{	
	/* 个人 我想要 详情 */
	$wantshare = get_wantshare_details($id);
	if($wantshare['sy_jine'] > 0 || $wantshare['start'] == 2){
		return true;
	}
	
	$sheep_id = $wantshare['sheep_id'];
	/* 商品详情 */
	$sheep = get_sheep_details($sheep_id);
	/* 购买羊支付  余额 */
	$time = gmtime();
	$dangqian = local_date($GLOBALS['_CFG']['time_format'], $time); 
	
	/* 默认时间 */
	$bonus_time_yue = $dangqian;
	$bonus_time = $time;
	$bonus_time_done = $time;
	if($sheep['cycle'] > 0){
		$bonus_time_yue = date("Y-m-d H:i:s", strtotime("+1 months", strtotime($dangqian)));
		$bonus_time = strtotime(date ($bonus_time_yue));
		$bonus_time_done_yue = date("Y-m-d H:i:s", strtotime("+".$sheep['cycle']." months", strtotime($dangqian)));
		$bonus_time_done = strtotime(date ($bonus_time_done_yue));
	}
	$userset = get_user_set($wantshare['user_id']);
	
	/* 价值  */
	$sheep_price = $sheep['price'] ;

	$order = array(
		'sheep_id' => $sheep_id,/* 羊编号 */
		'user_id' => isset($wantshare['user_id']) ? $wantshare['user_id'] : $wantshare['user_id'],/* 用户编号 */
		'sheep_number' => 1,/* 数量  */
		'sheep_price' => $sheep_price,/* 价格  */
		'add_time' => $time,/* 时间  */
		'pay_type' => 'balance',/* 时间  */
		'pay_time' => gmtime(),/* 时间  */
		'state' => '2',/* 上级id  */
		'parent_id' => '',/* 上级id  */
		'hd_types' => '2',/* 活动类型  */
		'bonus' => $sheep['bonus'] / 12,/* 分红比例  */
		'cycle' => $sheep['cycle'],/* 分红月  */
		'bonus_time' => $bonus_time,/* 下一次分红时间  当前时间 加一个月  */
		'bonus_time_yue' => $bonus_time_yue,/* 下一次分红时间  当前时间 加一个月  */
		'bonus_time_done' => $bonus_time_done,/* 最终分红时间  */
		'bonus_time_done_yue' => $bonus_time_done_yue,/* 最终分红时间  */
	);		
	$GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('sheep_order'), $order, 'INSERT');
	$order_id = $db->insert_id();
	$sql = "UPDATE ". $GLOBALS['ecs']->table('sheep_me') ." SET start = '2'WHERE id= '". $id ."'";
	$GLOBALS['db']->query($sql);
	/* 购买通知  */
	$order['order_id'] = $order_id;
	if($userset['wxid'] ){
		wx_msg($userset['wxid'],10,$order);
	}  
	/* 根据订单ID 生成排队分成队列 */
	bonus_queue($order_id);	

 
}


/*
	验证身份证
  */
function validation_filter_id_card($id_card){
    if(strlen($id_card)==18){
        return idcard_checksum18($id_card);
    }elseif((strlen($id_card)==15)){
        $id_card=idcard_15to18($id_card);
        return idcard_checksum18($id_card);
    }else{
        return false;
    }
}
// 计算身份证校验码，根据国家标准GB 11643-1999
function idcard_verify_number($idcard_base){
    if(strlen($idcard_base)!=17){
        return false;
    }
    //加权因子
    $factor=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
    //校验码对应值
    $verify_number_list=array('1','0','X','9','8','7','6','5','4','3','2');
    $checksum=0;
    for($i=0;$i<strlen($idcard_base);$i++){
        $checksum += substr($idcard_base,$i,1) * $factor[$i];
    }
    $mod=$checksum % 11;
    $verify_number=$verify_number_list[$mod];
    return $verify_number;
}
// 将15位身份证升级到18位
function idcard_15to18($idcard){
    if(strlen($idcard)!=15){
        return false;
    }else{
        // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
        if(array_search(substr($idcard,12,3),array('996','997','998','999')) !== false){
            $idcard=substr($idcard,0,6).'18'.substr($idcard,6,9);
        }else{
            $idcard=substr($idcard,0,6).'19'.substr($idcard,6,9);
        }
    }
    $idcard=$idcard.idcard_verify_number($idcard);
    return $idcard;
}
// 18位身份证校验码有效性检查
function idcard_checksum18($idcard){
    if(strlen($idcard)!=18){
        return false;
    }
    $idcard_base=substr($idcard,0,17);
    if(idcard_verify_number($idcard_base)!=strtoupper(substr($idcard,17,1))){
        return false;
    }else{
        return true;
    }
}


?>